package com.intexh.quickandroid.module.chat.ChatManager;

import android.support.v4.util.Pair;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.intexh.quickandroid.module.chat.bean.ChatMessage;
import com.intexh.quickandroid.module.chat.bean.ChatSession;
import com.intexh.quickandroid.module.chat.event.NewMessageReceivedEvent;
import com.intexh.quickandroid.module.chat.util.PlayerUtil;
import com.intexh.quickandroid.utils.GsonUtils;
import com.intexh.quickandroid.utils.LogCatUtil;
import com.intexh.quickandroid.utils.Settings;
import com.intexh.quickandroid.utils.ValidateUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * Created by frank on 2016/6/3.
 *消息接收工具类
 */
public enum EasemobUtil {

    INSTANCE;
    private int count = 1;
    public void init() {
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }
    EMMessageListener msgListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            handleMessage(messages);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }

    };

    private void handleMessage(List<EMMessage> messages){
        EMClient.getInstance().chatManager().importMessages(messages);
        for (EMMessage message:messages) {
            String content;
            String attributeMessage = null;
            if(message.getType() == EMMessage.Type.IMAGE || message.getType() == EMMessage.Type.VOICE){
                EMFileMessageBody body = (EMFileMessageBody) message.getBody();
                content= body.getRemoteUrl();
            }else{
                EMTextMessageBody body = (EMTextMessageBody) message.getBody();
                content = body.getMessage();
            }
            try {
                attributeMessage = message.getStringAttribute("ext");
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            if(!ValidateUtils.isValidate(attributeMessage))return;
            LogCatUtil.e("frank","收到聊天消息："+attributeMessage);
            ChatMessage chatMessage= GsonUtils.jsonToBean(attributeMessage,ChatMessage.class);
            if(chatMessage.is_group()) {
                chatMessage.setEasemob_id(chatMessage.getEasemob_id());
            }else {
                chatMessage.setEasemob_id(message.getFrom());
            }
            chatMessage.setId(UUID.randomUUID().toString());
            chatMessage.setContent(content);
            chatMessage.save();
            //更新chatFragment
            ChatSession chatSession;
            chatSession=ChatSession.getSession(message.getFrom());
            if(chatSession==null){
                chatSession=new ChatSession();
            }
            if(chatMessage.is_group()) {
                chatSession.setSessionId(chatMessage.getEasemob_id());
                chatSession.setGroup_name(chatMessage.getGroup_name());
                chatSession.setGroup_avatar(chatMessage.getGroup_avatar());
            }else {
                chatSession.setSessionId(message.getFrom());
            }
            chatSession.setIsGroup(chatMessage.is_group());
            chatSession.setAvatar(chatMessage.getAvatar());
            chatSession.setName(chatMessage.getDisplay_name());
            chatSession.setCreateTime(System.currentTimeMillis());
            chatSession.setNotReadCount(chatSession.getNotReadCount()+1);   //存储未读条数
            chatSession.setLastMessage(GsonUtils.serializedToJson(chatMessage));
            chatSession.save();
            EventBus.getDefault().post(new NewMessageReceivedEvent(chatMessage)); //接收到新消息
            //true 表示消息免打扰
            if(!Settings.getBoolean(Settings.CHAT_MESSAGE_DO_NOT_DISTURB,false)){
                PlayerUtil.INSTANCE.playerVibrator();
                PlayerUtil.INSTANCE.playSystemMusic();
            }
        }
    }

    public List<ChatSession> getConversationList(){
        final List<ChatSession> mList=new ArrayList<>();
        final List<EMConversation> conversationList=loadConversationList();

        for (int i=0;i<conversationList.size();i++){
            EMMessage mEMMessage=conversationList.get(i).getLastMessage();
            String data=mEMMessage.getBody().toString().substring(5,(mEMMessage.getBody().toString()).length()-1);
            ChatMessage message=GsonUtils.jsonToBean(data,ChatMessage.class);
            ChatSession session=new ChatSession();
            session.setAvatar(message.getAvatar());
            session.setName(message.getDisplay_name());
            session.setLastMessage(data);
            session.setSessionId(mEMMessage.getFrom());
            mList.add(session);
        }
        return mList;
    }

    public List<ChatSession> getAllChatSessions(){
        List<ChatSession> all = ChatSession.getAll();
        return all;
    }
    public int getAllUnReadCount(){
        return ChatSession.getAllUnread();
    }






    protected List<EMConversation> loadConversationList(){
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }


    /**
     * 根据最后一条消息的时间排序
     *
     * @param
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }



/*    protected void onConversationInit(){
        // 获取当前conversation对象
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();
        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }

    }*/


}
